package com.kingmed.kmss.admin.modules.ums.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.kingmed.kmss.admin.modules.ums.mapper.UmsHrEmployeeMapper;
import com.kingmed.kmss.admin.modules.ums.model.UmsAdmin;
import com.kingmed.kmss.admin.modules.ums.model.UmsAdminOrganizationRelation;
import com.kingmed.kmss.admin.modules.ums.model.UmsHrEmployee;
import com.kingmed.kmss.admin.modules.ums.model.UmsOrganization;
import com.kingmed.kmss.admin.modules.ums.service.*;
import com.kingmed.kmss.common.constant.common.CommonConstants;
import com.kingmed.kmss.common.dto.admin.ums.HRQueryDTO;
import com.kingmed.kmss.common.enums.admin.UserSource;
import com.kingmed.kmss.common.enums.admin.UserStatus;
import com.kingmed.kmss.common.enums.admin.UserType;
import com.kingmed.kmss.common.exception.BusinessException;
import com.kingmed.kmss.common.utils.MessageUtils;
import com.kingmed.kmss.framework.feign.client.hr.RemoteHRSService;
import feign.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * EHR员工表(数据中台接口) 服务实现类
 * </p>
 *
 * @author WYL
 * @since 2022-12-29
 */
@Slf4j
@Service
public class UmsHrEmployeeServiceImpl extends ServiceImpl<UmsHrEmployeeMapper, UmsHrEmployee> implements UmsHrEmployeeService {
    /** 每页查询数量 */
    private static final Integer HR_QUERY_PAGE_SIZE = 5000;

    /** 外围系统 用户 */
    private static final LambdaQueryWrapper<UmsAdmin> oaAdminWrapper =
            new LambdaQueryWrapper<UmsAdmin>().eq(UmsAdmin::getUserSource, UserSource.OA_USER.getUserType());
    /** CRM 用户 */
    private static final LambdaQueryWrapper<UmsAdmin> crmAdminWrapper =
            new LambdaQueryWrapper<UmsAdmin>().eq(UmsAdmin::getUserSource, UserSource.CRM_USER.getUserType());

    /** HR 用户有效的状态（在职，返聘，试用，3状态才会被认为有效账号，才能登录） */
    public static final List<String> userOKStatusList =
            Arrays.asList(UserStatus.OK.getCode(), UserStatus.REHIRE.getCode(), UserStatus.TRIAL.getCode());

    @Autowired
    private RemoteHRSService remoteHRSService;
    @Autowired
    private UmsAdminService umsAdminService;
    @Autowired
    private UmsOrganizationService organizationService;
    @Autowired
    private UmsAdminOrganizationRelationService relationService;
    @Autowired
    private UmsBpmnMembershipService bpmnMembershipService;

    @Override
    public int saveBatchData(List<UmsHrEmployee> data) {
        for (UmsHrEmployee datum : data) {
            this.saveOrUpdate(datum);
        }
        return data.size();
    }

    /**
     * 同步HR员工数据
     */
    @Transactional
    @Override
    public int refreshHRUserList() {
        // 数据库已有用户（全部用户，不能只是oa用户）
        List<UmsAdmin> oldOAData = umsAdminService.list();
        Map<String, Long> oldAdminMap = oldOAData.stream().collect(Collectors.toMap(UmsAdmin::getEmployeeNum, UmsAdmin::getId,(a, b) -> b));
        // 数据库组织
        List<UmsOrganization> orgList = organizationService.list();
        Map<String, Long> orgMap = orgList.stream().collect(Collectors.toMap(UmsOrganization::getOrgCode, UmsOrganization::getId,(a, b) -> b));

        return this.refreshHRUserList(oldAdminMap, orgMap);
    }

    /**
     * 获取HR系统用户信息列表
     */
    private int refreshHRUserList(Map<String, Long> oldAdminMap, Map<String, Long> orgMap) {
        this.getBaseMapper().clearHrEmployee();

        int totalSize = 0;
        Integer pageNum = 1;
        int endPageNum;
        // 分页查询组织
        do {
            try {
                HRQueryDTO queryDTO = new HRQueryDTO();
                queryDTO.setPageNum(pageNum);
                queryDTO.setPageSize(HR_QUERY_PAGE_SIZE);
                Response response = remoteHRSService.getEmployeeList(queryDTO);
                log.info("getHRUserList_response：{}", response);
                if (response != null && response.status() == HttpStatus.HTTP_OK) {
                    JSONObject jsonObject = JSONUtil.parseObj(IOUtils.toString(response.body().asInputStream(), StandardCharsets.UTF_8.toString()));
                    JSONObject data = jsonObject.getJSONObject("data");
                    if (data != null) {
                        totalSize = data.getInt("totalSize");
                        JSONArray records = data.getJSONArray("records");

                        List<UmsHrEmployee> hrEmployees = Lists.newArrayList();
                        records.forEach(item -> {
                            UmsHrEmployee employee = JSONUtil.toBean(JSONUtil.toJsonStr(item), UmsHrEmployee.class);
                            hrEmployees.add(employee);
                        });
                        this.handleHrEmployee(hrEmployees, oldAdminMap);
                    }
                }
                endPageNum = HR_QUERY_PAGE_SIZE * pageNum;
                pageNum++;
            } catch (Exception e) {
                log.error("获取HR系统员工信息列表失败" + e.getMessage());
                throw new BusinessException(MessageUtils.message("customer_admin_getHRUserList_error"));
            }
        } while (totalSize > endPageNum);

        // 添加用户与组织的关联关系
        this.addOrgRelation(orgMap);
        return totalSize;
    }

    private void handleHrEmployee(List<UmsHrEmployee> hrEmployees, Map<String, Long> oldAdminMap) {
        if (CollectionUtil.isNotEmpty(hrEmployees)) {
            this.saveBatch(hrEmployees);

            List<UmsAdmin> umsAdmins = Lists.newArrayList();
            hrEmployees.forEach(hrEmployee -> {
                UmsAdmin admin = new UmsAdmin();
                Long userId = oldAdminMap.get(hrEmployee.getUsercode());
                admin.setUsername(hrEmployee.getUsercode());
                admin.setUserType(UserType.SYS_USER.getUserType());
                admin.setId(userId);
                // 如果是已有用户，不重置UserSource=oa
                if (userId == null) {
                    admin.setUserSource(UserSource.OA_USER.getUserType());
                }
                admin.setHrUserId(hrEmployee.getFid());
                admin.setHrOrgId(hrEmployee.getOrgid());
                admin.setEmployeeNum(hrEmployee.getUsercode());
                admin.setOaId(hrEmployee.getUsercode());
                admin.setPhone(hrEmployee.getMobile());
                admin.setNickName(hrEmployee.getUsername());
                admin.setOrgFullName(hrEmployee.getOrgname());
                admin.setEmpStatus(hrEmployee.getEmpstatus());
                //判断status=1
                admin.setStatus(userOKStatusList.contains(hrEmployee.getEmpstatus()) ? 1 : 0);
                admin.setDeleteFlag(CommonConstants.FLG_NO);
                admin.setDirectLeader(hrEmployee.getManagercode());
                admin.setDirectLeaders(hrEmployee.getManagerscode());

                // 记录最新的时间，不使用原来的OA时间
                //admin.setCreateTime(hrEmployee.getCreatetime()); //设置创建时间
                //admin.setUpdateTime(hrEmployee.getLastmodifiedtime()); //设置更新时间(会被框架覆盖)
                umsAdmins.add(admin);
            });
            umsAdminService.saveOrUpdateBatch(umsAdmins);
        }
    }

    /**
     * 添加用户与组织的关联关系
     */
    private void addOrgRelation(Map<String, Long> orgMap) {
        // 数据库已有外围系统用户
        List<UmsAdmin> adminOAData = umsAdminService.list(oaAdminWrapper);
        // 自建用户
        List<UmsAdmin> adminCrmData = umsAdminService.list(crmAdminWrapper);

        List<Long> crmAdminId = Lists.newArrayList();
        for (UmsAdmin adminCrmDatum : adminCrmData) {
            crmAdminId.add(adminCrmDatum.getId());
        }
        if (!CollectionUtils.isEmpty(adminOAData)) {
            List<UmsAdminOrganizationRelation> relationList = relationService.list(new LambdaQueryWrapper<UmsAdminOrganizationRelation>().in(UmsAdminOrganizationRelation::getAdminId, adminOAData.stream().map(UmsAdmin::getId).collect(Collectors.toList())));
            Map<Long, List<UmsAdminOrganizationRelation>> relationMap = relationList.stream().collect(Collectors.groupingBy(UmsAdminOrganizationRelation::getAdminId));
            List<UmsAdminOrganizationRelation> relations = Lists.newArrayList();
            for (UmsAdmin admin : adminOAData) {
                UmsAdminOrganizationRelation relation = new UmsAdminOrganizationRelation();
                List<UmsAdminOrganizationRelation> umsAdminOrganizationRelations = relationMap.get(admin.getId());
                if (umsAdminOrganizationRelations != null && !umsAdminOrganizationRelations.isEmpty()) {
                    relation = umsAdminOrganizationRelations.get(0);
                }
                relation.setAdminId(admin.getId());
                relation.setOrgId(orgMap.get(admin.getHrOrgId()));
                //设置创建更新时间
                relation.setCreateTime(admin.getCreateTime());
                relation.setUpdateTime(admin.getUpdateTime());
                relations.add(relation);
            }
            // 先删除 排除CRM自建用户
//            int deleteSize = this.getBaseMapper().clearAdminOrgRelation(crmAdminId);
//            log.info("addOrgRelation_clearAdminOrgRelation：{}", deleteSize);
            // 保存
            relationService.saveOrUpdateBatch(relations);
            // 更新审批角色与用户关联关系表
            for (UmsAdminOrganizationRelation relation : relations) {
                bpmnMembershipService.updateBranchRegion(relation.getAdminId());
            }
        }
    }
}
